package com.TheyChat.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.TheyChat.service.config.auth.RsaUtil;
import com.TheyChat.service.config.auth.TokenUtil;
import com.TheyChat.service.config.auth.entity.UserAuthInfo;
import com.TheyChat.service.config.core.enums.StatusEnum;
import com.TheyChat.service.config.core.exception.BusinessException;
import com.TheyChat.service.interfaces.dto.LoginRequest;
import com.TheyChat.service.interfaces.entity.User;
import com.TheyChat.service.interfaces.mapper.UserMapper;
import com.TheyChat.service.interfaces.service.IUserService;
import com.TheyChat.service.interfaces.vo.LoginVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.rsa.RSAUtil;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private RsaUtil rsaUtil;

    @Override
    public LoginVO login(LoginRequest request) {
        if (StrUtil.isBlank(request.getUsername()) && StrUtil.isBlank(request.getPhoneNumber()))
            throw new BusinessException("请输入用户名或者手机号");
        if (StrUtil.isBlank(request.getPassword()))
            throw new BusinessException("请输入密码");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(request.getUsername()))
            wrapper.eq("username", request.getUsername());
        if (StrUtil.isNotBlank(request.getPhoneNumber()))
            wrapper.eq("phone_number", request.getPhoneNumber());
        wrapper.eq("status", StatusEnum.VALID);
        List<User> userList = baseMapper.selectList(wrapper);
        if (ObjectUtil.isNotEmpty(userList) && userList.size() > 1)
            throw new BusinessException("系统错误，用户名/手机号被多个用户使用，请联系管理员处理");
        if (userList == null || userList.isEmpty())
            throw new BusinessException("用户不存在");
        User user = userList.get(0);
        LoginVO res = new LoginVO();
        String storageDecodePwd = rsaUtil.decoder(user.getPassword());
        String loginDecodePwd = rsaUtil.decoder(request.getPassword());
        if (!storageDecodePwd.equals(loginDecodePwd)) {
            res.setToken("");
//            res.setUserType(0);
            throw new BusinessException("账号或密码错误");
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String now = sdf.format(new Date());
            System.out.println("用户登录:" + user.getUsername() + "\ntimestamp:" + now);
            user.setLastLogin(now);
            baseMapper.updateById(user);
            UserAuthInfo uai = new UserAuthInfo();
            BeanUtil.copyProperties(user, uai);
            uai.setUserPwd(user.getPassword());
            uai.setUserType(user.getUserType());
            res.setToken(TokenUtil.sign(uai));
            res.setId(user.getId());
            res.setLoginTime(now);
            res.setUsername(user.getUsername());
            res.setUserType(user.getUserType());
            res.setMessage("登录成功");
        }
        return res;
    }
}
